<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加学生到班级</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <h1>班级用户</h1>
      <el-row :gutter="20">
        <el-col :span="13">
          <el-dropdown @command="handleCommand">
            <el-button class="el-dropdown-link">
              请选择班级<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="Class in this.classlist" :key="Class.id" :command="Class.id" v-text="Class.name"></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="11">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.searchInfo" clearable @clear="handleCommand(this.NowClass.id)">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <br>
      <el-row :gutter="20">
        <el-col :span="10">
          <span style="color: gray"><i class="el-icon-place"></i> 您当前所选班级: <el-tag> {{this.NowClass.name}}</el-tag></span>
        </el-col>
        <el-col :span="12">
          <span style="color: gray"><i class="el-icon-user"></i> 授课老师：<el-tag type="info"> {{this.NowClass.teacher}}</el-tag></span>
        </el-col>
      </el-row>
      <br>
      <!--        用户列表区域-->
      <el-collapse v-show="this.NowClass.name === '暂 无' ? false : true"  v-model="activeNames" @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <b>该班级所有学生信息</b><i class="header-icon el-icon-info"></i>
          </template>
          <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            :default-sort="{ prop: 'username', order: 'descending'}" :data="pageStuForm">
            <el-table-column fixed type="index" label="#"></el-table-column>
            <el-table-column align="center" prop="username" sortable label="学号"></el-table-column>
            <el-table-column align="center" prop="name" sortable label="姓名"></el-table-column>
            <el-table-column align="center" label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <!--              删除班级-->
                <el-tooltip effect="dark" content="删除班级" placement="top">
                  <el-button  type="danger" icon="el-icon-delete" size="mini" :enterable="false" @click="DelStu(scope.row.username)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!--      分页区域-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="queryInfo.pagesize"
            :pager-count="11"
            hide-on-single-page
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-collapse-item>
      </el-collapse>
      <div v-show="this.NowClass.name === '暂 无' ? false : true">
        <h1>学生用户</h1>
        <el-button class="new_btn" @click="StuDialogVisible = true">
          <svg class="icon_add" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <polygon id="路径" fill="#FFFFFF" points="11.34223 8.55450006 11.34223 1.52678484 8.5311359 1.52678484 8.5311359 8.55450006 1.50342068 8.55450006 1.50342068 11.3655941 8.5311359 11.3655941 8.5311359 18.3933093 11.34223 18.3933093 11.34223 11.3655941 18.3699652 11.3655941 18.3699652 8.55450006"></polygon>
          </svg>
          批量添加学生
        </el-button>
      </div>
    </el-card>
    <!--    批量添加学生用户的对话框-->
    <el-dialog
      title="批量添加学生用户"
      :visible.sync="StuDialogVisible"
      width="50%" @close="StuDialogClosed" class="role-mask">
      <!--      内容主体区-->
      <h4>每行一名学生用户，学号、姓名用空格分开。</h4>
      <el-form :model="StuToForm" status-icon ref="StuToFormRef">
        <el-form-item prop="text">
          <el-input type="textarea" v-model="StuToForm.text" :autosize="{ minRows:6, maxRows: 16}" placeholder="学号1 姓名1
学号2 姓名2
... ...
... ..." required></el-input>
        </el-form-item>
      </el-form>
      <!--      嵌套展现表格-->
      <el-dialog
        width="50%"
        title="批量添加学生用户"
        :visible.sync="innerVisible"
        append-to-body class="role-mask">
        <el-table
          v-loading="loading1"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          height="300" :default-sort="{ prop: 'username', order: 'ascending'}" :data="addStuForm">
          <el-table-column fixed type="index" sortable label="序号"></el-table-column>
          <el-table-column align="center" prop="name" label="姓名">
            <template slot-scope="scope">
              <el-tag>{{scope.row.name}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="username" sortable label="学号"></el-table-column>
        </el-table>
        <div style="margin-top:12px"></div>
          <span slot="footer">
            <el-row>
                 <el-col :span="4" :offset="5" >
                    <el-button class="white_btn" @click="clear">取 消</el-button>
                </el-col>
                <el-col :span="4" :offset="5">
                    <el-button class="new_btn" type="primary" @click="addStu">添 加</el-button>
                </el-col>
            </el-row>
        </span>
      </el-dialog>
      <!--              底部按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetStu">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="addtoTable()">添 加</el-button>
          </el-col>
        </el-row>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'


export default {
  name: 'StuToClass',
  data () {
    return {
      queryInfo: {
        // 模糊搜索
        searchInfo: '',
        // 当前页数
        pagenum: 1,
        pagesize: 10
      },
      loading: true, // 班级所有学生加载
      loading1: true, // 批量添加学生用户
      // 该老师所有的班级
      classlist: [],
      // id查班级下的学生
      StuForm: [],
      NowClass: {
        name: '暂 无',
        id: '',
        teacher: '暂 无'
      },
      total: 0,
      activeNames: ['1'],
      StuDialogVisible: false,
      // 添加学生到班级
      StuToForm: {
        text: ''
      },
      innerVisible: false,
      // 表格展示
      xuehao: ['暂无数据'],
      addStuForm:{
        username:'',
        name:''
      }
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    async getClassList () {
      const { data: res } = await this.$http.get('/class/allOfTeacher/' + localStorage.getItem('username'))
      if (res.status !== 200) {
        return this.$message.error('获取班级列表失败!')
      }
      this.classlist = res.data
    },
    async handleCommand (id) {
      this.NowClass.id = id
      const { data: res } = await this.$http.get('/student/allStudentOfClass/' + id)
      if (res.status !== 200) {
        return this.$message.error('获取班级学生列表失败!')
      }
      this.StuForm = res.data.student
      this.NowClass.name = res.data.class.name
      this.NowClass.teacher = res.data.class.teacher
      console.log(res.data)
      console.log(this.StuForm)
      if (this.StuForm.length === res.data.student.length){
        this.total = this.StuForm.length
        this.loading = false
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.handleCommand(this.NowClass.id)
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.handleCommand(this.NowClass.id)
    },
    async DelStu (StuId) {
      const confirmResult = await this.$confirm('此操作将从该班级永久删除此学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      ).catch(err => err)
      // 若用户确认删除，则返回值为字符串 confirm
      // 若取消删除，返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      var StuToClass = []
      StuToClass.push({ classId: this.NowClass.id, stuId: StuId })
      console.log(StuToClass)
      axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
      const { data: res } = await this.$http.delete('/student/deleteFromClass/', {data: StuToClass})
      if (res.status !== 200) {
        return this.$message.error('从该班级删除学生失败！')
      }
      this.$message.success('从该班级删除学生成功!')
      this.handleCommand (this.NowClass.id)
    },
    handleChange (val) {
      console.log(val)
    },
    // 监听批量添加学生用户对话框的关闭事件
    StuDialogClosed () {
      this.$refs.StuToFormRef.resetFields()
    },
    resetStu () {
      this.$refs.StuToFormRef.resetFields()
    },
    addtoTable () {
      var table = this.StuToForm.text.split('\n')
      var a = []
      var b = []
      var arr = []
      var i = 0
      while (table[i]) {
        a = table[i]
        b = a.split(' ')
        this.xuehao[i] = b[0] + ' ' + b[1]
        i = i + 1
        arr.push({username: b[0],name: b[1]})
        // console.log(b)
      }
      this.addStuForm = arr
      console.log(this.addStuForm)
      if (this.addStuForm.length === arr.length){
        this.loading1 = false
        this.innerVisible = true
      }
    },
    // 点击按钮，批量添加学生用户
    addStu () {
      this.$refs.StuToFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 调用接口进行批量添加学生用户
        axios.defaults.headers['Content-Type'] = 'application/text;charset=utf-8'
        const { data: res } = await this.$http.post('/student/addToClass/' + this.NowClass.id, this.StuToForm.text)
        if (res.status !== 200) {
          return this.$message.error('批量添加失败！')
        }
        this.$message.success('批量添加成功!')
        console.log(res)
        // 隐藏批量添加学生用户的对话框
        this.StuDialogVisible = false
        this.innerVisible = false
        this.handleCommand (this.NowClass.id)
      })
    },
    // 清空数据
    clear () {
      this.innerVisible = false
      this.xuehao = ['暂无数据']
    }
  },
  computed: {
    pageStuForm: function () {
      var search = this.queryInfo.searchInfo
      if (search) {
        return this.StuForm.filter(function (data) {
          return Object.keys(data).some(function (key) {
            return String(data[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.StuForm.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
    }
  }
}
</script>

<style scoped>
  .new_btn{
    background: #545c64;
    color: white;
    letter-spacing: 2px;
  }
  .new_btn:hover,.new_btn:focus{
    background: #545c99;
    color: ghostwhite;
    letter-spacing: 2px;
  }
  .white_btn{
    color: #545c64;
    letter-spacing: 2px;
  }
  .white_btn:hover,.white_btn:focus{
    background: #545c99;
    color: ghostwhite;
    letter-spacing: 2px;
  }
  .icon_add{
    width: 26px;
    height: 26px;
    padding-right: 4px;
    vertical-align:middle;
  }
</style>
